package com.ajmd.onlineexam.baseUtil;

import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONObject;

import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @author ajmd
 * @since 2023/3/13 2:44
 */
@Component
public class MyTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if(request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        response.setCharacterEncoding("utf-8");
        //前端vue将token添加在请求头中
        String token = request.getHeader("authorization");
        if(token != null){
            DecodedJWT decodedJWT = JWTUtils.verify(token);
            if(ObjectUtils.isNotEmpty(decodedJWT)){
                System.out.println("通过拦截器");
                System.out.println("当前时间:"+ LocalDateTime.now());
                System.out.println("过期时间:"+decodedJWT.getExpiresAt());
                return true;
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try{
            JSONObject json = new JSONObject();
            json.put("message","token认证失败");
            json.put("code",HttpServletResponse.SC_UNAUTHORIZED);
            json.put("data",new HashMap<>());
            out = response.getWriter();
            out.append(json.toJSONString());
            System.out.println("认证失败，未通过拦截器!!!");

        }catch (Exception e){
            e.printStackTrace();
            response.sendError(500);
        }finally {
            if (out != null) {
                out.close();
            }
            return false;
        }
    }
}
